package com.jron.cqiu.kernel.util;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-12
 * @Time: 21:48:04
 */
public class SingletonFactory implements SingletonStrategy {

    /**
     * 单例类全名
     */
    private String singletonClassName = null;

    /**
     * 单例实例
     */
    private Object singletonInstance = null;

    public SingletonFactory() {
    }

    public Object instance() {
        return singletonInstance;
    }

    /**
     * 重置单例策略实现类
     */
    public void reset() {
        if (singletonClassName != null) {
            Class clazz = null;
            try {
                clazz = Thread.currentThread().getContextClassLoader().loadClass(singletonClassName);
                singletonInstance = clazz.newInstance();
            } catch (Exception e) {
                System.out.println("Got a exception when SingletonFactory.reset : " + e.getMessage());
                try {
                    clazz = Class.forName(singletonClassName);
                    singletonInstance = clazz.newInstance();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        }
    }

    /**
     * @param singletonClassName
     */
    public void setSingletonClassName(String singletonClassName) {
        this.singletonClassName = singletonClassName;
        reset();
    }

    /**
     * 创建单例
     *
     * @param className 需要创建单例的类全名
     * @return
     */
    public static SingletonStrategy createSingleton(String className) {
        SingletonStrategy result = null;
        try {
            result = (SingletonStrategy) Class.forName(defaultSingletonClass).newInstance();
        } catch (Exception e) {
            System.out.println("Got a exception when SingletonFactory.createSingleton : " + e.getMessage());
            result = new SingletonFactory();
        }

        result.setSingletonClassName(System.getProperty(className, className));
        return result;
    }

}
